package com.huahan.auth.security.config;

import com.huahan.auth.granter.AppTokenGranter;
import com.huahan.auth.granter.DDTokenGranter;
import com.huahan.auth.granter.SmsCodeTokenGranter;
import com.huahan.auth.granter.WXTokenGranter;
import com.huahan.auth.mapper.UserInfoMapper;
import com.huahan.auth.security.component.MyRedisTokenStore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    /**
     * 注入用于支持 password 模式
     */
    @Resource
    private AuthenticationManager authenticationManager;
    @Lazy
    @Resource(name = "userDetailsServiceBean")
    private UserDetailsService userDetailsService;

    @Resource
    private DataSource dataSource;

    @Resource
    private WebResponseExceptionTranslator customOAuth2ResponseExceptionTranslator;

    @Resource
    private MyRedisTokenStore tokenStore;

    /**
     * 设置用户密码的加密方式
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public ClientDetailsService jdbcClientDetailsService() {
        return new JdbcClientDetailsService(dataSource);
    }

    @Resource
    private UserInfoMapper userInfoDao;

    /**
     * 添加自定义授权类型
     *
     * @return List<TokenGranter>
     */
    private TokenGranter tokenGranter(final AuthorizationServerEndpointsConfigurer endpoints) {
        List<TokenGranter> granters = new ArrayList<TokenGranter>(Collections.singletonList(endpoints.getTokenGranter()));

        AuthorizationServerTokenServices tokenServices = endpoints.getTokenServices();
        ClientDetailsService clientDetailsService = endpoints.getClientDetailsService();
        OAuth2RequestFactory oAuth2RequestFactory = endpoints.getOAuth2RequestFactory();

        SmsCodeTokenGranter smsCodeTokenGranter = new SmsCodeTokenGranter(tokenServices, clientDetailsService, oAuth2RequestFactory);
        smsCodeTokenGranter.setAccountService(userInfoDao);
        granters.add(smsCodeTokenGranter);


        //PC授权登录
        AppTokenGranter appTokenGranter = new AppTokenGranter(tokenServices, clientDetailsService, oAuth2RequestFactory);
        appTokenGranter.setAccountService(userInfoDao);
        granters.add(appTokenGranter);

        //wx授权登录
        WXTokenGranter wxTokenGranter = new WXTokenGranter(tokenServices, clientDetailsService, oAuth2RequestFactory);
        wxTokenGranter.setAccountService(userInfoDao);
        granters.add(wxTokenGranter);

        //wx授权登录
        DDTokenGranter ddTokenGranter = new DDTokenGranter(tokenServices, clientDetailsService, oAuth2RequestFactory);
        ddTokenGranter.setAccountService(userInfoDao);
        granters.add(ddTokenGranter);

        return new CompositeTokenGranter(granters);
    }


    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .tokenGranter(tokenGranter(endpoints))
                .tokenStore(tokenStore)
                .exceptionTranslator(customOAuth2ResponseExceptionTranslator);

        // 用于支持密码模式
        endpoints.authenticationManager(authenticationManager);

        // userDetailsService refresh_token
        endpoints.userDetailsService(userDetailsService);
    }
    /*
     *
     * 授权服务安全配置
     *
     * @throws Exception
     */

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer)
            throws Exception {
        oauthServer.passwordEncoder(passwordEncoder());

        oauthServer
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients();
    }

    /**
     * 授权客户端配置
     *
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 客户端配置
        clients.withClientDetails(jdbcClientDetailsService());
    }
}
